package com.mes.handler.job;

import java.math.BigDecimal;
import java.util.Map;
import org.apache.log4j.Logger;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.hibernate.Query;
import org.openbravo.client.kernel.BaseActionHandler;
import org.openbravo.dal.core.OBContext;
import org.openbravo.dal.service.OBDal;
import org.openbravo.database.SessionInfo;
import org.openbravo.model.ad.access.User;

@SuppressWarnings("unchecked")
public class EmesoJobOrderDataInfoHandler extends BaseActionHandler {
	private static Logger logger = Logger.getLogger(EmesoJobOrderDataInfoHandler.class);
	
	@Override
	protected JSONObject execute(Map<String, Object> parameters, String content) {
		JSONObject message = new JSONObject();
		try {
			OBContext.setAdminMode();
			JSONObject request = new JSONObject(content);
			String code = request.getString("code");
			
			return search(code);
		} catch (Exception e) {
			logger.error("查询作业订单信息异常：" + e.getMessage(), e);
			try {
				message.put("result", false);
				message.put("text", "查询作业订单信息异常：" + e.getMessage());
			} catch (JSONException e1) {
			}
		} finally {
			OBContext.restorePreviousMode();
		}
		return message;
	}
	
	private JSONObject search(String code) {
		JSONObject responseResult = new JSONObject();
		try {
			Map map = this.getOrderInfo(code);
			if (map == null) {
				responseResult.put("result", false);
				responseResult.put("desc", "未找到作业订单[" + code + "]");
				return responseResult;
			}
			//查询上道工序已完工数量(得到当前工序可开工数量)
			long canQty = getCanStartWork((String)map.get("manuOrderId"), map.get("routeNo") + "");
			if (canQty > 0) {
				map.put("canQtyStart", canQty - (Long)map.get("qtyStart"));
			} else if (canQty == 0) {
				map.put("canQtyStart", 0);
			}
			responseResult.put("orderInfo", map);
			User user = OBDal.getInstance().get(User.class, SessionInfo.getUserId());
			responseResult.put("userName", user.getName());
			
			responseResult.put("result", true);
			OBDal.getInstance().commitAndClose();
		} catch (Exception e) {
			OBDal.getInstance().rollbackAndClose();
			e.printStackTrace();
			logger.error("查询作业订单信息异常：" + e.getMessage(), e);
			try {
				responseResult.put("result", false);
				responseResult.put("desc", "查询作业订单信息异常：" + e.getMessage());
			} catch (JSONException ex) {
			}
		}
		return responseResult;
	}
	
	/**
	 * 验证是否有已开工，未完工订单
	private void checkJobOrderExe(String code, JSONObject responseResult) throws JSONException {
		Query query = OBDal.getInstance().getSession().createQuery(
				"from Emeso_ManuOrder_Job_Exe e where e.emesoManuorderJobOrder.code=? and status='CREATE'");
		query.setParameter(0, code);
		EmesoManuOrderJobExe jobExe = (EmesoManuOrderJobExe) query.uniqueResult();
		if (jobExe != null) {
			responseResult.put("orderExeCode", jobExe.getCode());
			responseResult.put("qtyStart", jobExe.getQty());
		}
	}
	 */
	
	private Map getOrderInfo(String code) throws Exception {
		String hql = "select new map(jo.emesoManuorder.id as manuOrderId,jo.emesoManuorder.code as manuOrderCode, " +
				"jo.product.name as productName, jo.product.name2 as productName2, jo.product.searchKey as productCode," +
				"jo.routeNo as routeNo, jo.routeName as routeName, jo.processTime as processTime, " +
				"station.name as station, jo.batchNo as batchNo, jo.seqNo as seqNo, jo.description as description," +
				"jo.planedDateFrom as dateForm, jo.planedDateTo as dateTo, dep.name as department, " +
				"g.name as resourceGroup, r.name as resource, jo.status as orderStatus, jo.qty as qty, " +
				"jo.qtyStart as qtyStart, (jo.qty - jo.qtyStart) as canQtyStart) " +
				"from Emeso_ManuOrder_Job_Order jo " +
				"left join jo.emesStation station " +
				"left join jo.emesDepartment dep " +
				"left join jo.emesResourceGroup g " +
				"left join jo.emesResource r " +
				"where jo.code = :code";
		return (Map)OBDal.getInstance().getSession().createQuery(hql).setParameter("code", code).uniqueResult();
	}
	
	/**
	 * 通过作业订单的 工序 为条件 生产订单为条件 从 Emeso_ManuOrder_Job 找到记录则为上一道工序的记录
	 */
	private long getCanStartWork(String manuOrderId, String routeNo) throws Exception {
		String sql = "select Emes_Get_Can_Start_Work(?, ?) from dual";
		Query query = OBDal.getInstance().getSession().createSQLQuery(sql);
		query.setParameter(0, manuOrderId);
		query.setParameter(1, routeNo);
		BigDecimal obj = new BigDecimal(query.uniqueResult() + "");
		if (obj == null) {
			return 0;
		}
		return obj.longValue();
	}
}
